package cn.fjc920.siaa.activitys

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.DatePickerDialog
import android.content.Context
import android.content.SharedPreferences
import android.icu.util.Calendar
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.*
import cn.fjc920.siaa.R
import cn.fjc920.siaa.activityutils.BaseActivity
import cn.fjc920.siaa.fragments.HomeFragment
import cn.fjc920.siaa.internetUtils.LoadingDialog
import cn.fjc920.siaa.internetUtils.OkhttpUtils
import kotlinx.android.synthetic.main.activity_add.*
import kotlinx.android.synthetic.main.activity_fast_add.*
import okhttp3.Request
import org.jsoup.Jsoup
import java.io.IOException

/**
 *      描述：快捷添加工时
 *      作者：樊建财
 *      时间：2023-02-28
 */

class FastAddActivity : BaseActivity(),  DatePickerDialog.OnDateSetListener{

    private lateinit var loadingDialog:LoadingDialog
    private lateinit var userName: String
    private lateinit var password: String
    private lateinit var loginDatas: HashMap<String, String>
    private lateinit var context: Context
    private lateinit var url: String
    private lateinit var sp: SharedPreferences
    private lateinit var _csrf:String

    private val createUrl = "${OkhttpUtils.url}item/create"
    private val projects = HashMap<String, String>()
    private val projectNames = ArrayList<String>()
    private val types = HashMap<String,String>()
    private val typeNames = ArrayList<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fast_add)

        init()
    }

    private fun init() {

        context = this
        setSupportActionBar(findViewById(R.id.fast_add_toolbar))
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        loadingDialog = LoadingDialog(context)

        url = "${OkhttpUtils.url}login"
        sp = getSharedPreferences("userData", Context.MODE_PRIVATE).apply {
            userName = getString("userName", "")!!
            password = getString("password", "")!!
            if (userName.length > 1 && password.length > 5) {
                loadingDialog.show("加载中...")
                login()
            } else {
                LoginActivity.actionStart(context)
                finish()
            }
        }
    }

    private fun login() {

        OkhttpUtils.getAsync(url, object : OkhttpUtils.DataCallBack {
            override fun requestFailure(request: Request?, e: IOException?) {
                Toast.makeText(context, "哇我！网络被外星人撸走了！", Toast.LENGTH_SHORT).show()
                finish()
            }

            override fun requestSuccess(result: String?) {

                //获取_csrf
                val doc = Jsoup.parse(result!!)
                val input = doc.select("input[type=hidden]")
                val element = input[0]
                val _csrf = element.attr("value")
                loginDatas = HashMap()
                loginDatas["username"] = userName
                loginDatas["password"] = password
                loginDatas["_csrf"] = _csrf
                loginDatas["remember-me"] = "on"

                OkhttpUtils.postAsync(url, loginDatas, object : OkhttpUtils.DataCallBack {

                    override fun requestFailure(request: Request?, e: IOException?) {
                        Toast.makeText(context, "登录超时，请检查网络", Toast.LENGTH_SHORT).show()
                    }

                    @SuppressLint("CommitPrefEdits")
                    override fun requestSuccess(result: String) {
                        val doc = Jsoup.parse(result)
                        //获取用户名
                        val un = doc.getElementById("avatar")!!.text()

                        if (userName == un) {
                            initListData()
                            initClick()
                        } else {
                            Toast.makeText(context, "登录已过期,请重新登录", Toast.LENGTH_SHORT).show()
                            LoginActivity.actionStart(context)
                            finish()
                            sp.edit().apply {
                                remove("userName")
                                remove("password")
                            }
                            OkhttpUtils.cookieStore.clear()
                        }
                    }
                })
            }
        })
    }

    private fun initClick() {
        fast_add_toolbar.setNavigationOnClickListener {
            finish()
        }

        fast_tv_date.setOnClickListener {
            datePickerShow()
        }

        fast_tv_project.setOnClickListener {
            showPd()
        }

        fast_tv_type.setOnClickListener {
            showTd()
        }

        //提交
        fast_btn_submit.setOnClickListener {
            submit()
        }
    }

    //填充下拉列表
    private fun initListData() {

        OkhttpUtils.getAsync(createUrl, object : OkhttpUtils.DataCallBack {
            override fun requestFailure(request: Request?, e: IOException?) {
                loadingDialog.dismiss()
                Toast.makeText(context,"加载数据失败，请检查网络！",Toast.LENGTH_SHORT).show()
                finish()
            }

            override fun requestSuccess(result: String) {
                val doc = Jsoup.parse(result)

                //获取_csrf
                val inputs = doc.getElementById("formCreateItem")!!.select("input[type=hidden]")
                val input = inputs[0]
                _csrf = input.attr("value")

                //获取项目名称及id
                val option = doc.getElementById("projectList")!!.getElementsByTag("option")
                for (ele in option) {
                    //获取项目名称
                    val name = ele.attr("value")
                    //获取项目id
                    val id = ele.attr("data-id")
                    projectNames.add(name)
                    projects[name] = id
                }

                //获取类型名称及id
                val option2 = doc.getElementById("workList")!!.getElementsByTag("option")
                for (ele in option2) {
                    //获取项目名称
                    val name = ele.attr("value")
                    //获取项目id
                    val id = ele.attr("data-id")
                    typeNames.add(name)
                    types[name] = id
                }
                loadingDialog.dismiss()
            }
        })
    }

    private fun showPd() {

        val t = ArrayList<String>()
        val inflater = layoutInflater
        val view = inflater.inflate(R.layout.project_dialog, null)
        val es = view.findViewById(R.id.ed_search) as EditText
        val rv = view.findViewById(R.id.rv_projects) as ListView
        val dialog = AlertDialog.Builder(this).setView(view).show()
        dialog.window!!.setBackgroundDrawableResource(R.drawable.drawable_round_edge)
        val arrayAdapter = ArrayAdapter<String>(
            context, android.R.layout.simple_list_item_1, projectNames
        )
        rv.adapter = arrayAdapter
        rv.setOnItemClickListener { parent, view, position, id ->
            if (t.isNotEmpty()) {
                fast_tv_project.text = t[position]
                dialog.dismiss()
            } else {
                fast_tv_project.text = projectNames[position]
                dialog.dismiss()
            }
        }

        //输入监听
        es.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                if (es.text.isNotEmpty()) {
                    t.clear()
                    for (name in projectNames) {
                        if (name.contains(es.text.toString())) {
                            t.add(name)
                        }
                    }
                    if (t.isNotEmpty()) {
                        rv.adapter = ArrayAdapter(
                            context,
                            android.R.layout.simple_list_item_1,
                            t
                        )
                    } else {
                        Toast.makeText(context, "无此项目", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    t.clear()
                    rv.adapter = ArrayAdapter(
                        context,
                        android.R.layout.simple_list_item_1,
                        projectNames
                    )
                }
            }

        })
    }

    @SuppressLint("InflateParams")
    private fun showTd() {

        val inflater = layoutInflater
        val view = inflater.inflate(R.layout.type_dialog, null)
        val rv = view.findViewById(R.id.rv_types) as ListView
        val dialog = AlertDialog.Builder(this).setView(view).show()
        dialog.window!!.setBackgroundDrawableResource(R.drawable.drawable_round_edge)
        val arrayAdapter = ArrayAdapter<String>(
            context, android.R.layout.simple_list_item_1, typeNames
        )
        rv.adapter = arrayAdapter
        rv.setOnItemClickListener { parent, view, position, id ->
            fast_tv_type.text = typeNames[position]
            dialog.dismiss()
        }
    }

    //提交数据
    private fun submit() {

        val maps = HashMap<String, String>()

        if (fast_tv_date.text.isEmpty()) {
            Toast.makeText(context, "日期为空！", Toast.LENGTH_SHORT).show()
        } else if (fast_tv_project.text.isEmpty()) {
            Toast.makeText(context, "项目名称为空！", Toast.LENGTH_SHORT).show()
        } else if (fast_tv_type.text.isEmpty()) {
            Toast.makeText(context, "工作类型为空！", Toast.LENGTH_SHORT).show()
        } else if (fast_ed_time.text.isEmpty()) {
            Toast.makeText(context, "工作时长为空！", Toast.LENGTH_SHORT).show()
        } else {
            maps["_csrf"] = _csrf
            maps["date"] = fast_tv_date.text.toString()
            maps["project2"] = fast_tv_project.text.toString()
            maps["projectId"] = projects.getValue(fast_tv_project.text.toString())
            maps["work2"] = fast_tv_type.text.toString()
            maps["workId"] = types.getValue(fast_tv_type.text.toString())
            maps["hour"] = fast_ed_time.text.toString()
            maps["comment"] = fast_ed_remark.text.toString()
            val loadingDialog = LoadingDialog(context)
            loadingDialog.show("加载中...")
            OkhttpUtils.postAsync(createUrl, maps, object : OkhttpUtils.DataCallBack {
                override fun requestFailure(request: Request?, e: IOException?) {
                    Toast.makeText(context, "提交失败请检查网络！", Toast.LENGTH_SHORT).show()
                    loadingDialog.dismiss()
                }

                override fun requestSuccess(result: String?) {
                    loadingDialog.dismiss()
                    Toast.makeText(context, "提交成功！", Toast.LENGTH_SHORT).show()
                    HomeFragment.apply {
                        homeTodayFragment.refresh()
                        homeAllFragment.refresh()
                    }
                }
            })
        }
    }

    private fun datePickerShow() {

        val calendar = Calendar.getInstance()
        val year = calendar[Calendar.YEAR]
        val month = calendar[Calendar.MONTH]
        val day = calendar[Calendar.DAY_OF_MONTH]

        DatePickerDialog(this, this, year, month, day).apply {
            setCancelable(true)
            show()
        }
    }

    override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
        var month = month
        month += 1
        val date = "${year}-${month}-$dayOfMonth"
        fast_tv_date.text = date
    }
}